package com.xt.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xt.back.dto.RewardMappingDto;
import com.xt.back.entity.RewardMapping;
import com.xt.back.mapper.RewardMapper;
import com.xt.back.mapper.RewardMappingMapper;
import com.xt.back.mapper.UserMapper;
import com.xt.back.service.IRewardMappingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户奖励关联表 服务实现类
 * </p>
 *
 * @author leotong
 * @since 2022-04-03
 */
@Service
@AllArgsConstructor
public class RewardMappingServiceImpl extends ServiceImpl<RewardMappingMapper, RewardMapping> implements IRewardMappingService {

    private final RewardMappingMapper rewardMappingMapper;

    private final RewardMapper rewardMapper;

    private final UserMapper userMapper;

    @Override
    public Page<RewardMappingDto> getRewardMappingByPage(RewardMapping rewardMapping) {
        Page<RewardMappingDto> result=new Page<>();
        Page<RewardMapping> page=new Page<>(rewardMapping.getPageNum(),rewardMapping.getPageSize());
        QueryWrapper<RewardMapping> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(rewardMapping.getRewardId()!=null&&!Objects.equals(rewardMapping.getRewardId(),""),RewardMapping::getRewardId,rewardMapping.getRewardId())
                .eq(rewardMapping.getUserId()!=null&&!Objects.equals(rewardMapping.getUserId(),""),RewardMapping::getUserId,rewardMapping.getUserId());
        Page<RewardMapping> rewardMappingPage = rewardMappingMapper.selectPage(page, queryWrapper);
        result.setTotal(rewardMappingPage.getTotal());
        result.setRecords(convert(rewardMappingPage.getRecords()));
        return result;
    }

    @Override
    public List<RewardMappingDto> getAllRewardMapping() {
        return convert(this.list());
    }

    public List<RewardMappingDto> convert(List<RewardMapping> rewardMappings){
        List<RewardMappingDto> result=new ArrayList<>();
        for (RewardMapping rewardMapping : rewardMappings) {
            RewardMappingDto rewardMappingDto=new RewardMappingDto();
            BeanUtils.copyProperties(rewardMapping,rewardMappingDto);
            System.out.println(rewardMapping.getRewardId());
            rewardMappingDto.setReward(rewardMapper.selectById(rewardMapping.getRewardId()));
            rewardMappingDto.setUser(userMapper.selectById(rewardMapping.getUserId()));
            result.add(rewardMappingDto);
        }
        return result;
    }
}
